<?php
/**
 * 简历 Logic
 */

namespace app\common\logic;

use app\common\exception\CustomException;
use app\common\model\BaseModel;
use app\common\model\Category;
use app\common\model\CategoryDistrict;
use app\common\model\CategoryJob;
use app\common\model\Company;
use app\common\model\Job;
use app\common\model\JobApply;
use app\common\model\Member;
use app\common\model\Resume;
use app\common\model\ResumeActivate;
use app\common\model\ResumeCandidate;
use app\common\model\ResumeCertificate;
use app\common\model\ResumeComplete;
use app\common\model\ResumeContact;
use app\common\model\ResumeEducation;
use app\common\model\ResumeExecuteLog;
use app\common\model\ResumeExecuteLogItems;
use app\common\model\ResumeIntention;
use app\common\model\ResumeLanguage;
use app\common\model\ResumeWork;
use app\common\model\Task;
use app\common\queue\Producer\ActivateProducerQueue;
use app\common\queue\Producer\CommonProducerQueue;
use phpService\PdfService;
use think\cache\driver\Redis;
use think\Db;
use Think\Exception;
use function GuzzleHttp\Psr7\str;

class ResumeLogic {

    /**
     * 简历导入
     */
    static function import($dataList, $companyId = 0,$execute_id = 0,$unique_key=null) {
        try{
            self::lockImport($dataList);
        }catch (CustomException $e){
            return return_data(500,$e->getMessage(),$e->getData());
        }
        if(!$execute_id){
            // 过滤掉手机号相同的数据
            $result = [];
            foreach ($dataList as $value){
                if(empty($value['basic']['contact']['mobile']) || !empty($result[$value['basic']['contact']['mobile']])){
                    continue;
                }
                $result[$value['basic']['contact']['mobile']] = $value;
            }
            $dataList = array_values($result);
            // 创建执行记录
            $execute_id = ResumeExecuteLog::add(['company_id'=>$companyId,'total_num'=>count($dataList)]);
        }
        $dataList = self::moreDataHandle($dataList,$companyId,$execute_id);
        if(!$dataList){
            return [];
        }

        $compelete_list = [];
        $contact_list = [];
        $intention_list = [];
        $certificate_list = [];
        $education_list = [];
        $language_list = [];
        $work_list = [];
        $category_data = model(Category::class)->getCache();
        $category_job_data = model(CategoryJob::class)->getCacheContent();
        $category_district_data = model(CategoryDistrict::class)->getCache();
        $memberModel = model(Member::class);
        $resumeModel = model(Resume::class);
        $resumeid_arr = [];

        Db::startTrans();
        try {

            $mobile_arr = [];
            foreach ($dataList as $key => $value) {
                if(empty($value['basic']['contact']['mobile'])){
                    continue;
                }
                $mobile_arr[] = $value['basic']['contact']['mobile'];
                // 处理激活数据 --- 手机号
                $activate_data['mobiles'][] = $value['basic']['contact']['mobile'];
            }
            if(empty($mobile_arr)){
                Db::rollback();
                return [];
            }
            // 处理激活数据 --- 企业id
            $activate_data['company_id'] = $companyId;

            $exist_members = $memberModel->where('company_id',$companyId)
                ->where('mobile','in', $mobile_arr)->column('uid,mobile,username','mobile');
            foreach ($dataList as $key => $value) {
                if(empty($value['basic']['contact']['mobile'])){
                    continue;
                }
                $_member_model = clone $memberModel;
                $_resume_model = clone $resumeModel;
//                $categorylist = array_column($value['intention_list'], 'category');
//                $exist_member = $_member_model->where('mobile', $value['basic']['contact']['mobile'])->find();
                $exist_member = $exist_members[$value['basic']['contact']['mobile']]??null;
                if ($exist_member) {
                    $resume_intention = ResumeIntention::where('uid',$exist_member['uid'])->field('rid,category_text')->find();
                    $resumeid_arr[] = $resume_intention['rid'];
                    //自动投递
                    self::jobApplyAdd($companyId, $exist_member['uid'], [$resume_intention['category_text']]);
                    continue; //TODO 更新
                }
                //插入member表
                $insert_data_member = [
                    'company_id' => $companyId,
                    'username' => config('global_config.reg_prefix') . $value['basic']['contact']['mobile'],
                    'password' => '',
                    'pwd_hash' => randstr(),
                    'mobile' => $value['basic']['contact']['mobile'],
                    'utype' => 2,
                    'platform' => $value['basic']['platform'] ?? ''
                ];
                $_member_model->validate(false)->allowField(true)->save($insert_data_member);
                $insert_uid = $_member_model->uid;
                //$insert_uid = 0;

                //插入resume表
                $insert_data_resume = [
                    'uid' => $insert_uid,
                    'service_tag' => '',
                    'fullname' => $value['basic']['fullname'],
                    'sex' => $value['basic']['sex'],
                    'birthday' => $value['basic']['birthday'],
                    'residence' => $value['basic']['residence'],
                    'height' => $value['basic']['height'],
                    'marriage' => array_search($value['basic']['marriage'], $_resume_model->map_marriage),
                    'education' => array_search($value['basic']['education'], model(BaseModel::class)->map_education),
                    'enter_job_time' => $value['basic']['enter_job_time'] ? strtotime($value['basic']['enter_job_time']) : 0,
                    'householdaddress' => $value['basic']['householdaddress'],
                    'major1' => 0,
                    'major2' => 0,
                    'major' => 0,
                    'current' => 0,
                    'click' => 0,
                    'custom_field_1' => '',
                    'custom_field_2' => '',
                    'custom_field_3' => '',
                    'platform' => $value['basic']['platform'] ?? '',
                    'remark' => '',
                    'comment' => '',
                    'audit' => 1,
                    'download_time' => isset($value['basic']['download_time']) ? strtotime($value['basic']['download_time']) : 0
                ];
                $_resume_model->validate(false)->save($insert_data_resume);
                $insert_resumeid = $_resume_model->id;
                if ($value['basic']['specialty'] != '') {
                    model(Resume::class)->where('id', $insert_resumeid)->setField('specialty', $value['basic']['specialty']);
                }

                $resumeid_arr[] = $insert_resumeid;
                // 联系方式
                $contact_list[] = [
                    'rid' => $insert_resumeid,
                    'uid' => $insert_uid,
                    'mobile' => $value['basic']['contact']['mobile'],
                    'email' => $value['basic']['contact']['email'] ?? '',
                    'qq' => '',
                    'weixin' => ''
                ];
                // 工作意图
                foreach ($value['intention_list'] as $k => $v) {
                    $arr = [
                        'rid' => $insert_resumeid,
                        'uid' => $insert_uid,
                        'nature' => array_search($v['nature'], $_resume_model->map_nature),
                        'category1' => 0,
                        'category2' => 0,
                        'category3' => 0,
                        'category' => 0,
                        'district1' => 0,
                        'district2' => 0,
                        'district3' => 0,
                        'district' => 0,
                        'minwage' => $v['minwage'],
                        'maxwage' => $v['maxwage'],
                        'trade' => array_search($v['trade'], $category_data['QS_trade']) === false ? 0 : array_search($v['trade'], $category_data['QS_trade'])
                    ];
                    $arr['district_text'] = $v['district'];
                    if(preg_match('/(.*)(\/|、)(.*)/',$v['district'],$match)){
                        $v['district'] = $match[3]??'';
                    }
//                    $district_arr = explode("/", $v['district']);
//                    $v['district'] = $district_arr[count($district_arr) - 1];
                    $district_id = array_search($v['district'], $category_district_data);
                    if(!$district_id){
                        $district_id = array_search($match[1]??'', $category_district_data);
                    }
                    if ($district_id !== false) {
                        $district_info = model(CategoryDistrict::class)->where('id', $district_id)->find();
                        if ($district_info !== null) {
                            if ($district_info['pid'] == 0) {
                                $arr['district1'] = $district_id;
                                $arr['district'] = $district_id;
                            } else {
                                $parent_district_info = model(CategoryDistrict::class)->where('id', $district_info['pid'])->find();
                                if ($parent_district_info['pid'] == 0) {
                                    $arr['district1'] = $parent_district_info['id'];
                                    $arr['district2'] = $district_id;
                                    $arr['district'] = $district_id;
                                } else {
                                    $arr['district1'] = $parent_district_info['pid'];
                                    $arr['district2'] = $parent_district_info['id'];
                                    $arr['district3'] = $district_id;
                                    $arr['district'] = $district_id;
                                }
                            }

                        }
                    }
                    $arr['category_text'] = $v['category'];
//                    $category_arr = explode("/", $v['category']);
//                    $v['category'] = $category_arr[count($category_arr) - 1];
                    $v['category'] = preg_replace('/\//','\/',$v['category']);
                    $category_id = current(array_keys(preg_grep('/'.$v['category'].'/',$category_job_data)));
//                    $category_id = array_search($v['category'], $category_job_data);
                    if ($category_id !== false) {
                        $category_info = model(CategoryJob::class)->where('id', $category_id)->find();
                        if ($category_info !== null) {
                            if ($category_info['pid'] == 0) {
                                $arr['category1'] = $category_id;
                                $arr['category'] = $category_id;
                            } else {
                                $parent_category_info = model(CategoryJob::class)->where('id', $category_info['pid'])->find();
                                if ($parent_category_info['pid'] == 0) {
                                    $arr['category1'] = $parent_category_info['id'];
                                    $arr['category2'] = $category_id;
                                    $arr['category'] = $category_id;
                                } else {
                                    $arr['category1'] = $parent_category_info['pid'];
                                    $arr['category2'] = $parent_category_info['id'];
                                    $arr['category3'] = $category_id;
                                    $arr['category'] = $category_id;
                                }
                            }

                        }
                    }
                    $intention_list[] = $arr;
                }
                // 证书
                if(isset($value['certificate_list'])){
                    foreach ($value['certificate_list'] as $k => $v) {
                        $obtaintime = substr(preg_replace('/[^\d-]/','',$v['obtaintime']),0,7);
                        $arr = [
                            'rid' => $insert_resumeid,
                            'uid' => $insert_uid,
                            'name' => $v['name'],
                            'obtaintime' => strtotime($obtaintime)
                        ];
                        $certificate_list[] = $arr;
                    }
                }
                // 教育
                foreach ($value['education_list'] as $k => $v) {
                    $arr = [
                        'rid' => $insert_resumeid,
                        'uid' => $insert_uid,
                        'starttime' => strtotime($v['starttime']),
                        'endtime' => strtotime($v['endtime']),
                        'todate' => 0,
                        'school' => $v['school'],
                        'major' => $v['major'],
                        'education' => array_search($v['education'], model(BaseModel::class)->map_education)
                    ];
                    $education_list[] = $arr;
                }
                // 语言等级
                foreach ($value['language_list'] as $k => $v) {
                    $arr = [
                        'rid' => $insert_resumeid,
                        'uid' => $insert_uid,
                        'language' => array_search($v['language'], $category_data['QS_language']) === false ? 0 : array_search($v['language'], $category_data['QS_language']),
                        'level' => array_search($v['level'], $category_data['QS_language_level']) === false ? 0 : array_search($v['level'], $category_data['QS_language_level'])
                    ];
                    $language_list[] = $arr;
                }
                // 工作经历
                foreach ($value['work_list'] as $k => $v) {
                    $starttime = preg_replace('/\./','-',$v['starttime']);
                    $endtime = preg_replace('/\./','-',$v['endtime']);
                    $arr = [
                        'rid' => $insert_resumeid,
                        'uid' => $insert_uid,
                        'starttime' => strtotime($starttime),
                        'endtime' => strtotime($endtime),
                        'todate' => $v['todate'] ?? 0,
                        'companyname' => $v['companyname'],
                        'jobname' => $v['jobname'],
                        'duty' => $v['duty']
                    ];
                    $work_list[] = $arr;
                }
                // 简历完成度
                $compelete_list[] = [
                    'rid' => $insert_resumeid,
                    'uid' => $insert_uid,
                    'basic' => 1,
                    'intention' => !empty($intention_list) ? 1 : 0,
                    'specialty' => $value['basic']['specialty'] == '' ? 0 : 1,
                    'education' => !empty($education_list) ? 1 : 0,
                    'work' => !empty($work_list) ? 1 : 0,
                    'training' => 0,
                    'project' => 0,
                    'certificate' => !empty($certificate_list) ? 1 : 0,
                    'language' => !empty($language_list) ? 1 : 0,
                    'tag' => 0,
                    'img' => 0
                ];
                //自动投递
                $categorylist = array_column($value['intention_list'], 'category');
                self::jobApplyAdd($companyId, $insert_uid, $categorylist);

                //加入候选人
                if (time() - $insert_data_resume['download_time'] < 3600 * 24 * 7) {
                    $candidateExist = model(ResumeCandidate::class)
                        ->where('company_id', $companyId)
                        ->where('resume_id', $insert_resumeid)
                        ->find();
                    if (!$candidateExist) {
                        model(ResumeCandidate::class)->data([
                            'company_id' => $companyId,
                            'resume_id' => $insert_resumeid,
                            'status' => 0
                        ], true)->isUpdate(false)->save();;
                    }
                }

            }

            unset($_member_model, $_resume_model);
            if (!empty($compelete_list)) {
                model(ResumeComplete::class)->saveAll($compelete_list);
            }
            if (!empty($contact_list)) {
                model(ResumeContact::class)->saveAll($contact_list);
            }
            if (!empty($intention_list)) {
                model(ResumeIntention::class)->saveAll($intention_list);
            }
            if (!empty($certificate_list)) {
                model(ResumeCertificate::class)->saveAll($certificate_list);
            }

            if (!empty($education_list)) {
                model(ResumeEducation::class)->saveAll($education_list);
            }
            if (!empty($language_list)) {
                model(ResumeLanguage::class)->saveAll($language_list);
            }
            if (!empty($work_list)) {
                model(ResumeWork::class)->saveAll($work_list);
            }
            if (!empty($resumeid_arr)) {
                model(Resume::class)->where('id', 'in', $resumeid_arr)->setField('audit', 1);
            }

            Db::commit();

            // 加入激活队列
            ActivateProducerQueue::action(['controller'=>ResumeActivate::class,'action'=>'add',] + $activate_data);
//            ResumeActivate::add($activate_data);

            // 执行完成更新
            ResumeExecuteLog::edit(['id'=>$execute_id,'num'=>count($dataList),'unique_key'=>$unique_key]);
            // 解锁
            self::lockImport($dataList,0);
        } catch (\Exception $e) {
            //die;
            Db::rollBack();
//            echo $e->getTraceAsString();
            dolog(__METHOD__.'Error',[$e->getMessage(),$e->getLine(),$e->getFile(),$e->getTraceAsString()]);
//            file_put_contents(ROOT_PATH.'public/Extra.log',__METHOD__.'Error:'.date('Y-m-d H:i:s').$e->getTraceAsString().PHP_EOL,FILE_APPEND);
            //exit;
            dolog(__METHOD__.'ErrorData',$dataList);
            self::lockImport($dataList,0);

            return false;
        }
        if (!empty($resumeid_arr)) {
//            model(Resume::class)->refreshSearchBatch($resumeid_arr);
        }



        return $resumeid_arr;
    }

    /**
     *多数据处理
     * @param $dataList
     * @param $companyId
     * @param $execute_id
     * @return array
     */
    private static function moreDataHandle($dataList,$companyId,$execute_id){
        $num_limit = 5;
        if(count($dataList) <= $num_limit){
            return $dataList;
        }
        $chunk = collection($dataList)->chunk($num_limit)->toArray();

        foreach ($chunk as $key=>$data){
            $insert_log[] = [
                'unique_key'=> $execute_id . '_'.$key,
                'company_id' => $companyId,
                'execute_id' => $execute_id,
                'data' => $data,
            ];
        }
        if(empty($insert_log)){
            return $first_ten??[];
        }
        ResumeExecuteLogItems::addBatch($insert_log);
        foreach ($insert_log as $key=> $value){
            if($key == 0){
                $first_ten = $value['data'];
                continue;
            }
            $queue = new CommonProducerQueue('zip_queue');
            $queue->action(['controller'=>self::class,'action'=>'handleImport','unique_key'=>$value['unique_key']]);
        }
        return $first_ten??[];
    }

    /**
     *导入根据手机号是否重复加锁
     * @param $data
     * @param int $lock 1加锁 0解锁
     * @return bool
     * @throws CustomException
     */
    private static function lockImport($data,$lock=1){
        // 目前只针对单文件上传
        foreach ($data as $key => $value) {
            if(empty($value['basic']['contact']['mobile'])){
                continue;
            }
            $mobile_arr[] = $value['basic']['contact']['mobile'];
        }
        if(empty($mobile_arr)){
            throw new CustomException('手机号为空');
        }
        $key = md5(json_encode($mobile_arr));
        $cache_name_lock = __METHOD__.'lock_'.$key;
        $redis = new Redis();
        if($lock){
            $redis_data = $redis->get($cache_name_lock);
            if(!$redis->setnx($cache_name_lock,json_encode($data),10)){
                dolog('mobile_exists',[$mobile_arr,json_decode($redis_data,1),$data]);
                throw new CustomException('手机号重复',$mobile_arr);
            }
        }else{
            $redis->rm($cache_name_lock);
        }
        return true;
    }

    /**
     *
     * @param $params
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function handleImport($params){
        if(empty($params['unique_key'])){
            return false;
        }
        $res = ResumeExecuteLogItems::where('unique_key',$params['unique_key'])->find();
        if(!$res){
            return false;
        }
        return self::import(json_decode($res['data'],1),$res['company_id'],$res['execute_id'],$res['unique_key']);
    }

    //申请职位
    static function jobApplyAdd($companyId, $uid, $categorylist) {

        //20231105 新增代码
        $jobId = 0;
        if(!empty($categorylist)){
            $cid = Db::name('category_job')->whereIn('name',$categorylist)
                ->whereOrRaw('content REGEXP "'.implode('~',$categorylist).'"')
                ->column('id');
            if(!empty($cid)){
                $cid = implode(',',$cid);
                $jobId = Db::name('job')->where('company_id',$companyId)
                    ->where('category1 in ('.$cid.') or category2 in ('.$cid.') or category3 in ('.$cid.')')
                    ->column('id');
                if(!empty($jobId)){
                    $jobId = $jobId[0];
                }else{
                    $jobId = 0;
                }
            }
        }
        //20231105 新增代码 end
        \think\Db::startTrans();
        try {

            //print_r($jobId);
            //20231105 新增代码 end

//            $jobId = model('Job')
//                ->where('company_id', $companyId)
//                ->whereIn('jobname', $categorylist)
//                ->value('id');
            if ($jobId==0) {
                $jobId = model(Job::class)
                    ->where('company_id', $companyId)
                    ->whereIn('jobname', '其他')
                    ->value('id');
                if (!$jobId) {
                    $jobId = self::addJob($companyId);
                }
            }
            if (!$jobId) {
                \think\Db::commit();
                return false;
            }

            $companyInfo = model(Company::class)->where('id', $companyId)->find();
            $jobInfo = model(Job::class)
                ->field('id,uid,jobname,audit,is_display')
                ->where('id', 'eq', $jobId)
                ->find();

            $resumeInfo = model(Resume::class)
                ->field('id,fullname,audit,enter_job_time,sex,education')
                ->where('uid', $uid)
                ->find();

            $exist = model(JobApply::class)->where('comid', $companyId)->where('resume_id', $resumeInfo['id'])->find();
            if ($exist) {
                \think\Db::commit();
                return true;
            }
            $input_data['comid'] = $companyInfo['id'];
            $input_data['companyname'] = $companyInfo['companyname'];
            $input_data['company_uid'] = $companyInfo['uid'];
            $input_data['jobid'] = $jobInfo['id'];
            $input_data['jobname'] = $jobInfo['jobname'];
            $input_data['personal_uid'] = $uid;
            $input_data['resume_id'] = $resumeInfo['id'];
            $input_data['fullname'] = $resumeInfo['fullname'];
            $input_data['note'] = $data['note'] ?? '';
            $input_data['addtime'] = time();
            $input_data['is_look'] = 0;
            $input_data['handle_status'] = 0;
            $input_data['source'] = 0;
            $input_data['platform'] = config('platform','web');

            $result = model(JobApply::class)->data($input_data, true)->isUpdate(false)->save();
            if (false !== $result) {
//                model(Task::class)->doTask($uid, 2, 'apply_job');
            }
            \think\Db::commit();
            return true;
        } catch (\Exception $e) {
            \think\Db::rollBack();
            dolog(__METHOD__.':Error',[$e->getMessage(),$e->getLine(),$e->getFile()]);
//            echo $e->getMessage();
//            exit;
//            var_dump($e->getMessage(),$e->getFile(),$e->getLine());die;
            return false;
        }
    }

    static function addJob($companyId) {
        $companyInfo = model('Company')->where('id', $companyId)->find();
        $uid = $companyInfo['uid'];
        $input_data = [
            'basic' => [
                'id' => 0,
                'uid' => $uid,
                'company_id' => $companyId,
                'jobname' => '其他',
                'stick' => 0,
                'nature' => 1,
                'category1' => 10,
                'category2' => 52,
                'category3' => 496,
                'category' => '',
                'experience' => 0,
                'education' => 0,
                'minwage' => '',
                'maxwage' => '',
                'age_na' => 1,
                'negotiable' => 1,
                'district1' => 110000,
                'district2' => 110100,
                'district3' => 110101,
                'content' => '其他',
                'address' => "",
                'map_lat' => 0,
                'map_lng' => 0,
                'map_zoom' => 0,
                'need_notice' => 0,
                'amount' => 0,
                'department' => '',
                'minage' => 0,
                'maxage' => 0,
                'coms_id' => '',
            ],
            'contact' => [
                'uid' => $uid,
                'use_company_contact' => 1,
                'contact' => '',
                'mobile' => '',
                'is_display' => 1,
                'is_secrecy' => 1
            ]
        ];
        $input_data['basic']['category'] =
            $input_data['basic']['category3'] > 0
                ? $input_data['basic']['category3']
                : ($input_data['basic']['category2'] > 0
                ? $input_data['basic']['category2']
                : $input_data['basic']['category1']);
        $input_data['basic']['district'] =
            $input_data['basic']['district3'] > 0
                ? $input_data['basic']['district3']
                : ($input_data['basic']['district2'] > 0
                ? $input_data['basic']['district2']
                : $input_data['basic']['district1']);
        $input_data['basic']['tag'] = !empty($input_data['basic']['tag'])
            ? implode(',', $input_data['basic']['tag'])
            : '';
        $setmeal = (new Member())->getMemberSetmeal($uid);
        $input_data['basic']['company_id'] = $companyId;
        $input_data['basic']['addtime'] = time();
        $input_data['basic']['refreshtime'] = $input_data['basic']['addtime'];
        $input_data['basic']['setmeal_id'] = $setmeal['setmeal_id']??0;
        //新添加的职位，根据配置赋值审核状态
        $input_data['basic']['audit'] = 1;
        $input_data['basic']['click'] = 0;
            $input_data['basic']['robot'] = 0;
        $input_data['basic']['is_display'] = 1;
        $input_data['basic']['stick'] = 0;
        $input_data['basic']['emergency'] = 0;
        $input_data['contact']['weixin'] = '';
        $input_data['contact']['telephone'] = '';
        $input_data['contact']['qq'] = '';
        $input_data['contact']['email'] = '';

        \think\Db::startTrans();
        try {
            $result = model('Job')
                ->validate(true)
                ->allowField(true)
                ->save($input_data['basic']);
            if (false === $result) {
                throw new \Exception(model('Job')->getError());
            }
            $jobid = model('Job')->id;
            $input_data['contact']['uid'] = $uid;
            $input_data['contact']['jid'] = $jobid;
            if ($input_data['contact']['use_company_contact'] == 1) {
                $result = model('JobContact')
                    ->allowField(true)
                    ->save($input_data['contact']);
            } else {
                $result = model('JobContact')
                    ->validate(true)
                    ->allowField(true)
                    ->save($input_data['contact']);
            }
            if (false === $result) {
                throw new \Exception(model('JobContact')->getError());
            }
            \think\Db::commit();
            return $jobid;
        } catch (\Exception $e) {
            \think\Db::rollBack();
//            print_r($e->getMessage());
//            exit;
//            var_dump($e->getMessage(),$e->getFile(),$e->getLine());die;
            dolog(__METHOD__.'Error',[$e->getMessage(),$e->getFile(),$e->getLine()]);
            return false;
        }
    }

    /**
     * 同步邮件
     * @param $emailId
     * @return array
     */
    static function syncEmail($emailId) {
        $resList = [];
        try {
            $emailInfo = model('ResumeEmail')->where(['id' => $emailId])->find();
            $email = new ResumeEmailLogic($emailInfo['name'], $emailInfo['pwd']);
            $total = $email->getTotalNum();

            for ($id = 1; $id <= $total; $id++) {
                $header = $email->getHeader($id);
                if (!$header) {
                    continue;
                }
                $title = $header['subject'];
                $time = $header['time'];

//                echo $id . "\n";
//                echo $title . "\n";
//                continue;

                //根据标题判断邮件是否同步过
                $exist = model('ResumeEmailList')->where(['email_id' => $emailId, 'title' => $title])->find();
                if ($exist) {
                    continue;
                }

                //下载附件
                $attachment = $email->getAttachment($id);

                //58同城解析邮件正文
                if (strpos($title, '58.com')) {
                    $body = $email->getBody($id);
                    if (!strpos($body, '来自58同城网的简历')) {
                        continue;
                    }
                    $attachment = self::saveBodyFile($title, $body);
                }

                if (!$attachment) {
                    continue;
                }

                //解析附件
                $dataList = ResumeParseLogic::fileParse($attachment, $title);
                if (empty($dataList)) {
                    //记录异常
                    $resList[] = [
                        'title' => $title,
                        'message' => '解析失败'
                    ];
                    continue;
                }

                //boss直聘解析邮件中文
                if (strpos($title, '【BOSS直聘】')) {
                    $mobile = $dataList[0]['mobile'] ?? ''; //从附件解析手机号
                    $body = $email->getBody($id);
                    $attachment = self::saveBodyFile($title, $body);
                    $dataList = ResumeParseLogic::fileParse($attachment, $title);
                    if (empty($dataList)) {
                        //记录异常
                        $resList[] = [
                            'title' => $title,
                            'message' => '解析失败'
                        ];
                        continue;
                    }
                    $dataList[0]['basic']['contact']['mobile'] = $mobile;
                    $dataList[0]['basic']['download_time'] = date('Y-m-d', $time);
                }

                //导入数据
                $res = self::import($dataList, $emailInfo['company_id']);
                if (!$res) {
                    //记录异常
                    $resList[] = [
                        'title' => $title,
                        'message' => '导入失败'
                    ];
                    continue;
                }

                //导入成功
                $body = $email->getBody($id);
                model('ResumeEmailList')->isUpdate(false)->data([
                    'email_id' => $emailId,
                    'title' => $title,
                    'body' => $body,
                    'attachment' => $attachment
                ], true)->save();

                $resList[] = [
                    'title' => $title,
                    'message' => '导入成功'
                ];
            }
            $email->close();

            return [
                'status' => true,
                'resList' => $resList
            ];
        } catch (\Exception $e) {
            return [
                'status' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    static function saveBodyFile($title, $body) {
        $tempDir = '/tmp/html';
        if (!is_dir($tempDir)) {
            mkdir($tempDir, 0777, true);
        }
        $attachment = $tempDir . '/' . md5($title) . '.html';
        file_put_contents($attachment, $body);
        return $attachment;
    }

    static function writeShowCache($id, $resume_module, $pageCache) {
        $where['id'] = $id;
        $basic = model('Resume')
            ->where($where)
            ->field(true)
            ->find();
        if ($basic === null) {
            return false;
        }

        $category_data = model('Category')->getCache();
        $category_major_data = model('CategoryMajor')->getCache();
        $category_job_data = model('CategoryJob')->getCache();
        $category_district_data = model('CategoryDistrict')->getCache();

        $basic_info['id'] = $basic['id'];
        $basic_info['uid'] = $basic['uid'];
        $basic_info['audit'] = $basic['audit'];
        $basic_info['high_quality'] = $basic['high_quality'];
        $basic_info['service_tag'] = $basic['service_tag'];
        $basic_info['residence'] = $basic['residence'];
        $basic_info['height'] = $basic['height'];
        $basic_info['specialty'] = $basic['specialty'];
        $basic_info['refreshtime'] = daterange_format(
            $basic['addtime'],
            $basic['refreshtime']
        );
        $basic_info['click'] = $basic['click'];
        $basic_info['custom_field_1'] = $basic['custom_field_1'];
        $basic_info['custom_field_2'] = $basic['custom_field_2'];
        $basic_info['custom_field_3'] = $basic['custom_field_3'];
        $basic_info['sex'] = $basic['sex'];
        $basic_info['sex_text'] = model('Resume')->map_sex[$basic['sex']];
        $basic_info['age'] = date('Y') - intval($basic['birthday']);
        $basic_info['education_text'] = isset(
            model('BaseModel')->map_education[$basic['education']]
        )
            ? model('BaseModel')->map_education[$basic['education']]
            : '';
        $basic_info['experience_text'] =
            $basic['enter_job_time'] == 0
                ? '无经验'
                : format_date($basic['enter_job_time']) . '经验';
        $basic_info['householdaddress'] = $basic['householdaddress'];
        $basic_info['tag_text_arr'] = [];
        if ($basic['tag'] != '') {
            $tag_arr = explode(',', $basic['tag']);
            foreach ($tag_arr as $k => $v) {
                if (
                    is_numeric($v) &&
                    isset($category_data['QS_resumetag'][$v])
                ) {
                    $basic_info['tag_text_arr'][] =
                        $category_data['QS_resumetag'][$v];
                } else {
                    $basic_info['tag_text_arr'][] = $v;
                }
            }
        }
        $basic_info['major_text'] = isset($category_major_data[$basic['major']])
            ? $category_major_data[$basic['major']]
            : '';

        $basic_info['current_text'] = isset(
            $category_data['QS_current'][$basic['current']]
        )
            ? $category_data['QS_current'][$basic['current']]
            : '';
        $basic_info['complete_percent'] = model('Resume')->countCompletePercent(
            $basic['id']
        );

        $basic_info['marriage_text'] = isset(
            model('Resume')->map_marriage[$basic['marriage']]
        )
            ? model('Resume')->map_marriage[$basic['marriage']]
            : '保密';

        $basic_info['photo_img_src'] =
            $basic['photo_img'] > 0
                ? model('Uploadfile')->getFileUrl($basic['photo_img'])
                : default_empty('photo', $basic_info['sex']);
        $return['base_info'] = $basic_info;

        //求职意向
        $intention_data = model('ResumeIntention')
            ->field('id,rid,uid', true)
            ->where(['rid' => ['eq', $basic['id']]])
            ->limit(3) // 【优化】简历详情页-导出简历，三条以上求职意向都显示第三意向问题   和武哥确认改为只显示3条  zch 2022.9.30
            ->select();
        $intention_list = [];
        foreach ($intention_data as $key => $value) {
            $tmp_arr = [];
            $tmp_arr['nature_text'] = isset(
                model('Resume')->map_nature[$value['nature']]
            )
                ? model('Resume')->map_nature[$value['nature']]
                : '全职';
            $tmp_arr['category_text'] = isset(
                $category_job_data[$value['category']]
            )
                ? $category_job_data[$value['category']]
                : '';
            $tmp_arr['district_text'] = isset(
                $category_district_data[$value['district']]
            )
                ? $category_district_data[$value['district']]
                : '';

            $tmp_arr['district_full_text'] = isset(
                $category_district_data[$value['district1']]
            )
                ? $category_district_data[$value['district1']]
                : '';
            if ($tmp_arr['district_full_text'] != '' && $value['district2'] > 0) {
                $tmp_arr['district_full_text'] .= isset(
                    $category_district_data[$value['district2']]
                )
                    ? '-' . $category_district_data[$value['district2']]
                    : '';
            }
            if ($tmp_arr['district_full_text'] != '' && $value['district3'] > 0) {
                $tmp_arr['district_full_text'] .= isset(
                    $category_district_data[$value['district3']]
                )
                    ? '-' . $category_district_data[$value['district3']]
                    : '';
            }

            $tmp_arr['wage_text'] = model('BaseModel')->handle_wage(
                $value['minwage'],
                $value['maxwage'],
                0
            );
            $tmp_arr['trade_text'] = isset(
                $category_data['QS_trade'][$value['trade']]
            )
                ? $category_data['QS_trade'][$value['trade']]
                : '';

            // 【新增】求职状态唯一展示
            $return['base_info']['nature_text_unique'] = !empty($return['base_info']['nature_text_unique']) ? $return['base_info']['nature_text_unique'] : $tmp_arr['nature_text'];
            // 【新增】薪资唯一展示
            $return['base_info']['wage_text_unique'] = !empty($return['base_info']['wage_text_unique']) ? $return['base_info']['wage_text_unique'] : $tmp_arr['wage_text'];

            $return['base_info']['intention_jobs_text'][] = $tmp_arr['category_text'];
            $return['base_info']['intention_district_text'][] = $tmp_arr['district_text'];
            $return['base_info']['intention_district_full_text'][] = $tmp_arr['district_full_text'];
            $intention_list[] = $tmp_arr;
        }
        if (!empty($return['base_info']['intention_jobs_text'])) {
            $return['base_info']['intention_jobs_text'] = array_unique($return['base_info']['intention_jobs_text']);
            $return['base_info']['intention_jobs_text'] = implode(",", $return['base_info']['intention_jobs_text']);
        }
        if (!empty($return['base_info']['intention_district_text'])) {
            $return['base_info']['intention_district_text'] = array_unique($return['base_info']['intention_district_text']);
            $return['base_info']['intention_district_text'] = implode(",", $return['base_info']['intention_district_text']);
        }

        if (!empty($return['base_info']['intention_district_full_text'])) {
            $return['base_info']['intention_district_full_text'] = array_unique($return['base_info']['intention_district_full_text']);
            $return['base_info']['intention_district_full_text'] = implode(" ; ", $return['base_info']['intention_district_full_text']);
        } else {
            $return['base_info']['intention_district_full_text'] = '';
        }

        $return['intention_list'] = $intention_list;

        //工作经历
        $work_list = model('ResumeWork')
            ->field('id,rid,uid', true)
            ->where(['rid' => ['eq', $basic['id']]])
            ->select();
        $return['work_list'] = $work_list;
        //教育经历
        $education_list = model('ResumeEducation')
            ->field('id,rid,uid', true)
            ->where(['rid' => ['eq', $basic['id']]])
            ->select();
        foreach ($education_list as $key => $value) {
            $education_list[$key]['education_text'] = isset(
                model('BaseModel')->map_education[$value['education']]
            )
                ? model('BaseModel')->map_education[$value['education']]
                : '';
        }
        $return['education_list'] = $education_list;
        //项目经历
        if ($resume_module['project']['is_display'] == 1) {
            $project_list = model('ResumeProject')
                ->field('id,rid,uid', true)
                ->where(['rid' => ['eq', $basic['id']]])
                ->select();
        } else {
            $project_list = [];
        }
        $return['project_list'] = $project_list;
        //培训经历
        if ($resume_module['training']['is_display'] == 1) {
            $training_list = model('ResumeTraining')
                ->field('id,rid,uid', true)
                ->where(['rid' => ['eq', $basic['id']]])
                ->select();
        } else {
            $training_list = [];
        }
        $return['training_list'] = $training_list;

        //语言能力
        if ($resume_module['language']['is_display'] == 1) {
            $language_data = model('ResumeLanguage')
                ->field('id,rid,uid', true)
                ->where(['rid' => ['eq', $basic['id']]])
                ->select();
            $language_list = [];
            foreach ($language_data as $key => $value) {
                $tmp_arr = [];
                $tmp_arr['language_text'] = isset(
                    $category_data['QS_language'][$value['language']]
                )
                    ? $category_data['QS_language'][$value['language']]
                    : '';
                $tmp_arr['level_text'] = isset(
                    $category_data['QS_language_level'][$value['level']]
                )
                    ? $category_data['QS_language_level'][$value['level']]
                    : '';
                $language_list[] = $tmp_arr;
            }
        } else {
            $language_list = [];
        }
        $return['language_list'] = $language_list;
        //证书
        if ($resume_module['certificate']['is_display'] == 1) {
            $certificate_list = model('ResumeCertificate')
                ->field('id,rid,uid', true)
                ->where(['rid' => ['eq', $basic['id']]])
                ->select();
        } else {
            $certificate_list = [];
        }
        $return['certificate_list'] = $certificate_list;
        //照片作品
        if ($resume_module['img']['is_display'] == 1) {
            $img_list = model('ResumeImg')->getList(['rid' => $basic['id'], 'audit' => 1]);
        } else {
            $img_list = [];
        }
        $return['img_list'] = $img_list;
        if ($pageCache['expire'] > 0) {
            model('PageMobile')->writeCacheByAlias('resumeshow', $return, $pageCache['expire'], $id);
        }
        return $return;
    }

    //获取简历详情
    static function getDetail($id, $userinfo) {
        $id = intval($id);
        $field_rule_data = model('FieldRule')->getCache();
        $field_rule = [
            'basic' => $field_rule_data['Resume'],
            'contact' => $field_rule_data['ResumeContact'],
            'intention' => $field_rule_data['ResumeIntention'],
            'education' => $field_rule_data['ResumeEducation']
        ];
        foreach ($field_rule as $key => $rule) {
            foreach ($rule as $field => $field_attr) {
                $_arr = [
                    'is_display' => intval($field_attr['is_display']),
                    'field_cn' => $field_attr['field_cn']
                ];
                $field_rule[$key][$field] = $_arr;
            }
        }
        $resume_module_data = model('ResumeModule')->getCache();
        $resume_module = [];
        foreach ($resume_module_data as $module_name => $module_attr) {
            $_arr = [
                'module_cn' => $module_attr['module_cn'],
                'is_display' => intval($module_attr['is_display'])
            ];
            $resume_module[$module_name] = $_arr;
        }
        //读取页面缓存配置
        $pageCache = model('PageMobile')->getCache('resumeshow');
        //如果缓存有效期为0，则不使用缓存
        if ($pageCache['expire'] > 0) {
            $return = model('PageMobile')->getCacheByAlias('resumeshow', $id);
        } else {
            $return = false;
        }
        if (!$return) {
            $return = self::writeShowCache($id, $resume_module, $pageCache);
            if ($return === false) {
                return false;
            }
        }
        $return['base_info']['fullname'] = model('Resume')->formatFullname([$return['base_info']['id']], $userinfo, true);
        $return['field_rule'] = $field_rule;
        $return['resume_module'] = $resume_module;

        //联系方式
        $getResumeContact = model('Resume')->getContact($return['base_info'], $userinfo);
        $return['show_contact'] = $getResumeContact['show_contact'];
        $return['show_contact_note'] = $getResumeContact['show_contact_note'];
        $return['contact_info'] = $getResumeContact['contact_info'];

        // 附件简历
        $enclosure_resume = model('ResumeEnclosure')->getEnclosure(['rid' => $id]);
        $return['enclosure_resume'] = $enclosure_resume;

        // 简历审核状态： 0|'待审核';1|'已通过';2|'未通过'
        if (1 === intval($return['base_info']['audit']) && !empty($return['intention_list'])) {
            $return['is_invalid'] = 0;
        } else {
            $return['is_invalid'] = 1;
        }
        return $return;
    }

    //导出简历
    static function exportPdf($id) {
        $uid = model('Resume')->where('id', $id)->value('uid');
        $userinfo = (object)model('Member')->where('uid', $uid)->field(true)->find()->toArray();

        $info = self::getDetail($id, $userinfo);
        if (empty($info)) {
            return false;
        }

        if ($userinfo != null && $userinfo->uid === $info['base_info']['uid']) {
            $resume = model('Resume')->where('uid', $userinfo->uid)->field('id,uid,fullname')->find();
            $info['base_info']['fullname'] = $resume['fullname'];
        }

        $info['base_info']['specialty'] = json_encode($info['base_info']['specialty'], JSON_UNESCAPED_UNICODE);
        $info['base_info']['specialty'] = json_decode(str_replace('\n', '<br>', $info['base_info']['specialty']), true);
        if ($info === false) {
            return false;
        }
        $resume_module_data = model('ResumeModule')->getCache();
        $resume_module = [];
        foreach ($resume_module_data as $module_name => $module_attr) {
            $_arr = [
                'module_cn' => $module_attr['module_cn'],
                'is_display' => intval($module_attr['is_display'])
            ];
            $resume_module[$module_name] = $_arr;
        }
        $info['resume_module'] = $resume_module;
        $getResumeContact = model('Resume')->getContact($info['base_info'], $userinfo);
        $show_contact = $getResumeContact['show_contact'];
        $content = '
        <div id="saveBox" class="resume_preview">
            <div>
                <div class="resume_name">' . $info['base_info']['fullname'] . '的个人简历 </div>
                <div class="data_wrapper">
                <div class="baseData">
                <div class="list">
                        <div>
                            <span>姓名：</span> ' . $info['base_info']['fullname'] . '
                        </div>
                    </div>
                    <div class="list">
                        <div>
                            <span>性别：</span> ' . $info['base_info']['sex_text'] . '
                        </div>
                    </div>
                    <div class="list">
                        <div>
                            <span>年龄：</span> ' . $info['base_info']['age'] . '岁 
                        </div>
                    </div>
                    <div class="list">
                        <div>
                            <span >工作经验：</span> ' . $info['base_info']['experience_text'] . '
                        </div>
                    </div>
                    <div class="list">
                        <div>
                            <span>学历：</span> ' . $info['base_info']['education_text'] . '
                        </div>
                    </div>';

        if ($info['field_rule']['basic']['marriage']['is_display'] === 1 && !empty($info['base_info']['marriage_text'])) {
            $content .= ' <div  class="list">
                        <div>
                            <span>婚姻状况：</span> ' . $info['base_info']['marriage_text'] . '
                        </div>
                    </div>';
        }

        if ($info['field_rule']['basic']['height']['is_display'] === 1 && !empty($info['base_info']['height'])) {
            $content .= '<div class="list">
                        <div>
                            <span>身高：</span> ' . $info['base_info']['height'] . ' CM
                        </div>
                    </div>';
        }

        if ($info['field_rule']['basic']['major']['is_display'] === 1 && !empty($info['base_info']['major_text'])) {
            $content .= '<div class="list">
                        <div>
                            <span>专业：</span> ' . $info['base_info']['major_text'] . '
                        </div>
                    </div>';
        }

        if ($info['field_rule']['basic']['householdaddress']['is_display'] === 1 && !empty($info['base_info']['householdaddress'])) {
            $content .= '<div class="list">
                        <div>
                            <span>籍贯：</span> ' . $info['base_info']['householdaddress'] . '
                        </div>
                    </div>';
        }

        if ($info['field_rule']['basic']['residence']['is_display'] === 1 && !empty($info['base_info']['residence'])) {
            $content .= '<div class="list">
                        <div>
                            <span>现居住地：</span> ' . $info['base_info']['residence'] . '
                        </div>
                    </div>';
        }

        # 头像
        $content .= '<div class="clearfix">
                    </div>
                </div>
                    <div class="photo">
                        <img style="width: 120px; height: 120px;" src="' . $info['base_info']['photo_img_src'] . '" />
                    </div>
                </div>
            </div>';


        # 求职意向
        if ($info['resume_module']['intention']['is_display'] === 1 && count($info['intention_list']) > 0) {
            $content .= '<div class="bottom-line">
                <div class="title">求职意向</div>
                <div class="intention_list">';
            for ($i = 0; $i < count($info['intention_list']); $i++) {
                if ($i < 3) {
                    $intention = '';
                    switch ($i) {
                        case 0:
                            $intention = '第一意向';
                            break;
                        case 1:
                            $intention = '第二意向';
                            break;
                        case 2:
                            $intention = '第三意向';
                            break;
                    }
                    $content .= ' <p>
                        <span>
                            ' . $intention . '：
                        </span>
                        [' . $info['intention_list'][$i]['district_text'] . ']' . $info['intention_list'][$i]['category_text'] . '，' . $info['intention_list'][$i]['nature_text'] . '，' . $info['intention_list'][$i]['wage_text'] . '/月
                    </p>';
                }
            }

            $content .= '</div>
            </div>';
        }

        # 联系方式
        $content .= '<div class="bottom-line">
                <div class="title">
                    联系方式
                </div>';

        if ($userinfo != null && $userinfo->uid === $info['base_info']['uid']) {
            $show_contact = 1;
            $resume_contact = model('ResumeContact')->where('rid', $id)->field('mobile,weixin,email,qq')->find();
            if ($resume_contact != null) {
                $info['contact_info'] = $resume_contact;
            }
        }

        if ($show_contact === 0) {
            $content .= '<div class="intention_list">
                    <p>
                        <span>
                            下载后查看联系方式
                        </span>
                    </p>
                </div>';
        } else {
            $content .= '<div class="intention_list">';

            if (!empty($info['contact_info']['mobile'])) {
                $content .= '<p><span>手机号：</span>' . $info['contact_info']['mobile'] . '</p>';
            }

            if (!empty($info['contact_info']['weixin'])) {
                $content .= '<p><span>微信：</span>' . $info['contact_info']['weixin'] . '</p>';
            }

            if (!empty($info['contact_info']['email'])) {
                $content .= '<p><span>邮箱：</span>' . $info['contact_info']['email'] . '</p>';
            }

            if (!empty($info['contact_info']['qq'])) {
                $content .= '<p><span>QQ：</span>' . $info['contact_info']['qq'] . '</p>';
            }

            $content .= '</div>';
        }

        $content .= '</div>';

        if ($info['resume_module']['specialty']['is_display'] === 1 && !empty($info['base_info']['specialty'])) {
            $content .= '<div class="bottom-line">
                <div class="title">
                    自我描述
                </div>
                <div class="intention_list">
                    <p style="white-space: pre-line;">
                        ' . $info['base_info']['specialty'] . '
                    </p>
                </div>
            </div>';
        }

        if ($info['resume_module']['education']['is_display'] === 1 && count($info['education_list']) > 0) {
            $content .= '<div class="bottom-line">
                <div class="title">
                    教育经历
                </div>
                <div class="undergo_con">';

            for ($i = 0; $i < count($info['education_list']); $i++) {
                $content .= '<div class="undergo_title">
                        <span>' .
                    date('Y-m', $info['education_list'][$i]['starttime']);
                if ($info['education_list'][$i]['todate'] === 1) {
                    $content .= ' ~ 至今';
                } else {
                    $content .= ' 至 ' . date('Y-m', $info['education_list'][$i]['endtime']);
                }
                $content .= '</span>
                        <p>
                            <span class="border">
                                ' . $info['education_list'][$i]['school'] . '
                            </span>
                            <span class="border">
                                ' . $info['education_list'][$i]['education_text'] . '
                            </span>
                            <span class="border">
                                ' . $info['education_list'][$i]['major'] . '
                            </span>
                        </p>
                    </div>';
            }


            $content .= '</div>
                </div>';
        }

        if ($info['resume_module']['work']['is_display'] === 1 && count($info['work_list']) > 0) {
            $content .= '<div class="bottom-line">
                <div class="title">
                    工作经历
                </div>';

            for ($i = 0; $i < count($info['work_list']); $i++) {
                $content .= '<div class="undergo_con">
                    <div class="undergo_title">
                        <span>
                            ' . date('Y-m', $info['work_list'][$i]['starttime']);
                if ($info['work_list'][$i]['todate'] === 1) {
                    $content .= ' ~ 至今';
                } else {
                    $content .= ' 至 ' . date('Y-m', $info['work_list'][$i]['endtime']);
                }

                $info['work_list'][$i]['duty'] = json_encode($info['work_list'][$i]['duty'], JSON_UNESCAPED_UNICODE);
                $info['work_list'][$i]['duty'] = json_decode(str_replace('\n', '<br>', $info['work_list'][$i]['duty']), true);
                $content .= '</span>
                        <p>
                            <span class="border">
                                ' . $info['work_list'][$i]['companyname'] . '
                            </span>
                            <span class="border">
                                ' . $info['work_list'][$i]['jobname'] . '
                            </span>
                        </p>
                    </div>
                    <div class="undergo_list" style="margin-top: -10px;">
                        <p>
                            <span>
                                工作内容：
                            </span>
                            ' . $info['work_list'][$i]['duty'] . '
                        </p>
                    </div>
                </div>';
            }

            $content .= '</div>';

        }

        if ($info['resume_module']['project']['is_display'] === 1 && count($info['project_list']) > 0) {
            $content .= '<div class="bottom-line">
                <div class="title">
                    项目经历
                </div>';


            for ($i = 0; $i < count($info['project_list']); $i++) {
                $content .= '<div class="undergo_con">
                    <div class="undergo_title">
                        <span>' . date('Y-m', $info['project_list'][$i]['starttime']);
                if ($info['project_list'][$i]['todate'] === 1) {
                    $content .= ' ~ 至今';
                } else {
                    $content .= ' 至 ' . date('Y-m', $info['project_list'][$i]['endtime']);
                }

                $info['project_list'][$i]['description'] = json_encode($info['project_list'][$i]['description'], JSON_UNESCAPED_UNICODE);
                $info['project_list'][$i]['description'] = json_decode(str_replace('\n', '<br>', $info['project_list'][$i]['description']), true);
                $content .= '</span>
                        <p>
                            <span class="border">
                                ' . $info['project_list'][$i]['projectname'] . '
                            </span>
                            <span class="border">
                                ' . $info['project_list'][$i]['role'] . '
                            </span>
                        </p>
                    </div>
                    <div class="undergo_list" style="margin-top: -10px;">
                        <p>
                            <span>
                                项目描述：
                            </span>
                            ' . $info['project_list'][$i]['description'] . '
                        </p>
                    </div>
                </div>';
            }
            $content .= '</div>';
        }

        if ($info['resume_module']['training']['is_display'] === 1 && count($info['training_list']) > 0) {
            $content .= '<div class="bottom-line">
                <div class="title">
                    培训经历
                </div>';

            for ($i = 0; $i < count($info['training_list']); $i++) {
                $content .= '<div class="undergo_con">
                        <div class="undergo_title">
                            <span>' . date('Y-m', $info['training_list'][$i]['starttime']);
                if ($info['training_list'][$i]['todate'] === 1) {
                    $content .= ' ~ 至今';
                } else {
                    $content .= ' 至 ' . date('Y-m', $info['training_list'][$i]['endtime']);
                }
                $info['training_list'][$i]['description'] = json_encode($info['training_list'][$i]['description'], JSON_UNESCAPED_UNICODE);
                $info['training_list'][$i]['description'] = json_decode(str_replace('\n', '<br>', $info['training_list'][$i]['description']), true);
                $content .= '</span>
                            <p>
                                <span class="border">
                                    ' . $info['training_list'][$i]['agency'] . '
                                </span>
                                <span class="border">
                                    ' . $info['training_list'][$i]['course'] . '
                                </span>
                            </p>
                        </div>
                        <div class="undergo_list" style="margin-top: -10px;">
                            <p>
                                <span>
                                    培训内容：
                                </span>
                                ' . $info['training_list'][$i]['description'] . '
                            </p>
                        </div>
                    </div>';
            }


            $content .= '</div>';
        }

        if ($info['resume_module']['certificate']['is_display'] === 1 && count($info['certificate_list']) > 0) {
            $content .= '<div class="certificate bottom-line">
                <div class="title">
                    获得证书
                </div>
                <div class="certificate_list">';

            for ($i = 0; $i < count($info['certificate_list']); $i++) {
                $content .= '
                        <p>
                            <span class="li-item">
                                <span class="border2">
                                    ' . $info['certificate_list'][$i]['name'] . '
                                </span>
                                <span class="border2">
                                        | ' . date('Y-m', $info['certificate_list'][$i]['obtaintime']) . '
                                </span>
                            </span>
                        </p>';
            }

            $content .= '</div></div>';
        }

        if ($info['resume_module']['language']['is_display'] === 1 && count($info['language_list']) > 0) {
            $content .= '<div class="language bottom-line">
                <div class="title">
                    语言能力
                </div>
                <div class="language_list">';

            for ($i = 0; $i < count($info['language_list']); $i++) {
                $content .= '
                            <p><span class="li-item">
                                <span class="border2">
                                    ' . $info['language_list'][$i]['language_text'] . '
                                </span>
                                <span class="border2">
                                        |
                                    ' . $info['language_list'][$i]['level_text'] . '
                                </span>
                            </span></p>';
            }

            $content .= '</div></div>';
        }

        $content .= '</div>';


        $api = new PdfService();
        //生成pdf

        $pdf_path = 'resumePdf' . DS . date('Ym') . DS;
        $upload_path = SYS_UPLOAD_PATH . $pdf_path;
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0777, true);
            chmod($upload_path, 0777);
        }

        $save_anme = $info['base_info']['fullname'] . '的个人简历-' . config('global_config.sitename');
        $file_name = $upload_path . $save_anme;

        $css = file_get_contents(PUBLIC_PATH . 'assets/css/download_resume.css');
        $css = '<style>' . $css . '</style>';
        $content = $css . html_entity_decode($content);

        $sitename = config('global_config.sitename') . '(' . config('global_config.sitedomain') . ')';
        $logo = config('global_config.logo');
        $logo_url = !empty($logo) ? model('Uploadfile')->getFileUrl($logo) : '';

        $data = [
            'file_name' => $file_name,
            'content' => $content,
            'title_header' => $logo_url,
            'title_footer' => $sitename,
            'is_down' => 1
        ];

        $api->strToPdf($data);

        $url = SYS_UPLOAD_DIR_NAME . DS . $pdf_path . $save_anme . '.pdf';
        return $url;
    }

}
